package com.xbfinal.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xbfinal.reggie.common.R;
import com.xbfinal.reggie.dto.DishDto;
import com.xbfinal.reggie.pojo.Category;
import com.xbfinal.reggie.pojo.Dish;
import com.xbfinal.reggie.pojo.DishFlavor;
import com.xbfinal.reggie.pojo.Employee;
import com.xbfinal.reggie.service.CategoryService;
import com.xbfinal.reggie.service.DishFlavorService;
import com.xbfinal.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class dishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 添加菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){

        //精确清理
        String key="dish"+dishDto.getCategoryId()+"_"+dishDto.getStatus();
        redisTemplate.delete(key);

        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("保存成功");
    }

    /**
     * 菜品信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){

        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(name != null,Dish::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        //执行分页查询
        dishService.page(pageInfo,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        List<Dish> records = pageInfo.getRecords();

        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }


    /**
     * 根据菜品id查询菜品基本信息和对应的口味
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getDishDto(@PathVariable("id") Long id){
        final DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 添加菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){

        //清理所有菜品的缓存
        //final Set keys = redisTemplate.keys("dish_*");
        //redisTemplate.delete(keys);

        //精确清理
        String key="dish"+dishDto.getCategoryId()+"_"+dishDto.getStatus();
        redisTemplate.delete(key);

        dishService.updateWithFlavor(dishDto);
        return R.success("保存成功");
    }

    /**
     *删除
     * 请求 URL: http://localhost:8080/dish?ids=1568491426675707905
     * 请求方法: DELETE
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> myDelete(String ids){

        //把ids切割成List
        //.stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList())
        List<String> List = Arrays.asList(ids.split(","));
        List<Long> idsList = List.stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());

        dishService.deleteWithFlavor(idsList);
        return R.success("删除成功");
    }

    /**
     * `停售`
     * 请求 URL: `http://localhost:8080/dish/status/0?ids=1413384757047271425`
     * 请求方法: `POST`
     */
    @PostMapping("/status/0")
    public R<String> stop(String ids){
        List<String> List = Arrays.asList(ids.split(","));
        List<Long> idsList = List.stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        final Dish dish = new Dish();
        for (Long id:idsList) {
            dish.setId(id);
            dish.setStatus(0);
            dishService.updateById(dish);
        }
        return R.success("停售成功");
    }

    /**
     * 起售
     * @param ids
     * @return
     */
    @PostMapping("/status/1")
    public R<String> starting (String ids){

        List<String> List = Arrays.asList(ids.split(","));
        List<Long> idsList = List.stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        final Dish dish = new Dish();
        for (Long id:idsList) {
            dish.setId(id);
            dish.setStatus(1);
            dishService.updateById(dish);
        }
        return R.success("起售成功");
    }

    /**
     * 根据条件查询对应的菜品数据
     * @param dish
     * @return
     */
//    @GetMapping("/list")
//    public R<List<Dish>> listR(Dish dish){
//        //查询条件对象
//         LambdaQueryWrapper<Dish> lambdaQueryWrapper
//                = new LambdaQueryWrapper();
//        lambdaQueryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
//        //添加起售状态的条件
//        lambdaQueryWrapper.eq(Dish::getStatus,1);
//        //添加排序
//        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByAsc(Dish::getUpdateTime);
//
//        final List<Dish> list = dishService.list(lambdaQueryWrapper);
//
//        return R.success(list);
//    }
    @GetMapping("/list")
    public R<List<DishDto>> listR(Dish dish){
        List<DishDto> dtoList=null;
        //先构造key
        String key="dish"+dish.getCategoryId()+"_"+dish.getStatus();

        //先从redis获取缓存数据，如果存在直接返回
        dtoList= (List<DishDto>)redisTemplate.opsForValue().get(key);
        if(dtoList!=null){
                //说明存在
            log.info("在redis中查询的数据");
            return R.success(dtoList);

        }


        //查询条件对象
        LambdaQueryWrapper<Dish> lambdaQueryWrapper
                = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //添加起售状态的条件
        lambdaQueryWrapper.eq(Dish::getStatus,1);
        //添加排序
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByAsc(Dish::getUpdateTime);

        final List<Dish> list = dishService.list(lambdaQueryWrapper);
        dtoList  = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            final Long id = item.getId();//当前菜品id
            LambdaQueryWrapper<DishFlavor>lambdaQueryWrapper1
                    =new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(DishFlavor::getDishId,id);
            final List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper1);
            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());

        //redis不存在，则查询数据库并加入缓存,设置1小时的缓存时间
        redisTemplate.opsForValue().set(key,dtoList,1, TimeUnit.HOURS);

        return R.success(dtoList);
    }
}
